<?php

include_once 'UserPage.php';
include_once 'DBConnection.php';

class UserPageDAO {
	private static $instance;
	
	private  function __construct() {
		
	}
	
	public static function getInstance() {
		if (!isset(self::$instance)) {
			$className = __CLASS__;
			self::$instance = new $className;
		}
		return self::$instance;		
	}
	
	public function getUserPage($userId) {
		$db=DBConnection::getInstance();
		$page=new UserPage();
		$result=null;		
		try{
			$result=$db->exec_select_query($page->getUserPageByUserIdStatement(),array($userId));
		}catch (PDOException $e) {
			echo "Error: ".$e->getMessage().'<br />';
		}
		if (!$result) {
			return null;			
		}
		$page=$this->fillUserPageStructure($result);
		return $page;
	}
	
	private function fillUserPageStructure($result) {
		$page=new UserPage();
		$page->setAbout($result[0]["about"]);
		$page->setCssUrl($result[0]["css_url"]);
		$page->setCustomHeader($result[0]["custom_header"]);
		$page->setPageTitle($result[0]["page_title"]);
		$page->setSubtitle($result[0]["page_subtitle"]);
		$page->setUserId($result[0]["user_id"]);
		$page->setViewType($result[0]["view_type"]);					
		return $page;
	} 
	
	public function addDefaultUserPage($userId, $login) {
		$db=DBConnection::getInstance();
		if ($db instanceof DBConnection) {
			try {
				$db->exec_param_transaction(UserPage::getAddDefaultUserPageStatement(),array($userId,$login,"",""));
			} catch (PDOException $e) {
				echo "Error: ".$e->getMessage().'<br />';
			}
		}
	}
	
	public function changeUserPage($userId, $userPage) {
		$db=DBConnection::getInstance();
		if (($db instanceof DBConnection) && ($userPage instanceof UserPage)) {
			try{			
				$db->exec_param_transaction(UserPage::getUpdatePageStatement(),array($userPage->getPageTitle(),
				$userPage->getPageSubtitle(),$userPage->getAbout(), $userPage->getViewType(),
				$userPage->getCssUrl(),$userPage->getCustomHeader(),$userId));
			}catch(PDOException $e) {
				echo 'Error: '.$e->getMessage().'<br />'; 
			}
		}
	}
}

?>